﻿using Finance.Infrastructrue.Interface;
using Finance.Domain;
using Finance.ErrorCode;
using MediatR;
using System.Collections.Generic;
using Finance.API.Read.Application.Command.FinancialCategoryCommand;
using Dapper;
using MySql.Data.MySqlClient;
using System.Text;
using System.Runtime.Intrinsics.X86;
using Finance.Infrastructrue.Implement;

namespace Finance.API.Read.Application.Hander.FinancialCategoryHander
{
    public class ShowFinancialCategoryHander:IRequestHandler<ShowFinancialCategoryCommand, APIPaging<FinancialCategory>>
    {
        
        ILogger<ShowFinancialCategoryCommand> logger;
        DatabaseContext db;

        public ShowFinancialCategoryHander(ILogger<ShowFinancialCategoryCommand> logger, DatabaseContext db)
        {
            this.logger = logger;
            this.db = db;
        }

        public  async Task<APIPaging<FinancialCategory>> Handle(ShowFinancialCategoryCommand request, CancellationToken cancellationToken)
        {
            APIPaging<FinancialCategory> res = new APIPaging<FinancialCategory>();
            StringBuilder sb = new StringBuilder();
            StringBuilder sq = new StringBuilder();
            try
            {

                sb.Append(@"SELECT
                          FinancialCategoryId,
                          CategoryNumber,
                          CategoryName,
                          Remark,
                          IsDel
                        FROM
                          financialCategory
                        WHERE
                          IsDel = FALSE");
                sq.Append(@"SELECT
                              COUNT(FinancialCategoryId)
                            FROM
                               financialCategory
                            WHERE
                              IsDel = FALSE");
                

                if (!string.IsNullOrEmpty(request.CategoryName))
                {
                    sb.Append(" AND CategoryName LIKE @CategoryName");
                    sq.Append(" AND CategoryName LIKE @CategoryName");
                }
                sb.Append(" ORDER BY FinancialCategoryId DESC LIMIT @PageSize OFFSET @offset ");
                var parameters = new
                {
                    CategoryName = $"%{request.CategoryName}%",
                    offset=(request.PageIndex-1) * request.PageSize,
                    request.PageSize
                };

                var pageData = await db.DapperConnection.QueryAsync<FinancialCategory>(sb.ToString(), parameters);
                int totalCount = await db.DapperConnection.ExecuteScalarAsync<int>(sq.ToString(), parameters);
                int totalPage = (int)Math.Ceiling(totalCount / (double)request.PageSize);



                res.PageDatas= pageData.ToList();
                res.TotalCount = totalCount;
                res.TotalPage= totalPage;
                res.Message = "财务数据财务类别显示成功";
                res.Code = APIEnum.Ok;
                return  res;
            }
            catch (Exception ex)
            {
                res.Code = APIEnum.Fail;
                res.Message =ex.Message;
                logger.LogError("财务数据财务类别显示失败" + ex.Message);
                return res;
            }

        }
    }
}
